package fr.bitstrip.sitn.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import fr.bitstrip.sitn.model.Utilisateur;

@Repository("usersDAO")
@Transactional
public class UsersDAO {
	@Autowired
    private SessionFactory sessionFactory;
	
	public Session getSession() {
 		return sessionFactory.getCurrentSession();
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
	     this.sessionFactory = sessionFactory;
	}
	
	public Utilisateur getUserByLogin(String principal) {
		Query q = getSession().createQuery("from Utilisateur WHERE login = :login");
		q.setString("login", principal);
		Utilisateur user = (Utilisateur) q.uniqueResult();
		return user;
	}
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void save(Utilisateur user) {
		getSession().saveOrUpdate(user);
	}
}